package com.yc;

import com.mysql.cj.protocol.Resultset;
import com.yc.bean.Resorder;
import com.yc.bean.Resuser;
import com.yc.commons.DBHelper;
import com.yc.model.CartItem;

import java.sql.*;
import java.util.Calendar;
import java.util.Set;

/**
 * @author zwei
 * @create 2024-06-13 19:15
 */
public class OrderBiz {
    /**
     * 以事务处理方式来添加订单
     * @param resorder
     * @param cartItems
     * @return
     */
    public int order(Resorder resorder, Set<CartItem>cartItems, Resuser resuser) throws SQLException {
        if (cartItems==null||cartItems.size()<=0){
            throw new RuntimeException("订单为空");
        }
        int result=0;
        DBHelper db=new DBHelper();
        Integer roid=0;
        //事务处理
        Connection connection=db.getConnection();
        connection.setAutoCommit(false);    //关闭隐式事务提交
        String sql="insert into resorder(  userid,address,tel,ordertime,deliverytime,ps,status  ) values(?,?,?,now(),?,?,0)";
        PreparedStatement pstmt=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//代表获取自动生成的id
        pstmt.setString(1,resuser.getUserid()+"");
        pstmt.setString(2,resorder.getAddress());
        pstmt.setString(3,resorder.getTel());
        pstmt.setString(4,resorder.getDeliverytime());
        pstmt.setString(5, resorder.getPs());
        pstmt.executeUpdate();
        //取自动生成的id
        ResultSet rs= pstmt.getGeneratedKeys();
        if (rs.next()){
            roid=rs.getInt(1);
        }
        //循环所有订单项 添加到数据表 resorderitem
        String sql2="insert into resorderitem(  roid,fid,dealprice,num) values(?,?,?,?)";
        for (CartItem ci:cartItems){
            pstmt=connection.prepareStatement(sql2);
            pstmt.setString(1,roid+"");
            pstmt.setString(2,ci.getFood().getFid()+"");
            pstmt.setString(3,ci.getFood().getRealprice()+"");
            pstmt.setString(4,ci.getNum()+"");
            pstmt.executeUpdate();
        }
        connection.commit();
        return result;
    }
}
